<?php

namespace Home\Model;

use Think\Model;

class GradegoodsModel extends Model {

    protected $tableName = 'grade_goods'; 
    
    //某一会员等级为空时，则取其前一级的折扣为其折扣
    function get_pre_discount($grade, $goods_id) {
        if ($grade == 1) {
            return 1;
        }
        $info = $this->field('min(grade_discount) as max_discount')->where("goods_id=" . $goods_id . " AND grade < " . $grade . " AND grade_discount >= 0 ")->find();
        $result = $info[0]['max_discount'] ? $info[0]['max_discount'] : 1;
        return $result;
    }

    function get_user_discount($user_id, $goods_id) {
        if (!$user_id) {
            return;
        }
        $grade_discount = array();
        $Member_mod = M('member');
        $Ugrade_mod = M('ugrade');
        $member = $Member_mod->where('user_id='.$user_id)->find();
        if (!$member) {
            return;
        }
        $ugrade = $Ugrade_mod->where('grade=' . $member['ugrade'])->find();
        $grade_discount = $this->where('goods_id=' . $goods_id . ' AND grade_id=' . $ugrade['grade_id'])->find();
        if (!$grade_discount['grade_discount']) {
            $grade_discount['grade_discount'] = $this->get_pre_discount($member['ugrade'], $goods_id);
        }
        return $grade_discount['grade_discount'];
    }

}

?>
